package com.sgb.member.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberCompanyWebBinding;
import com.sgb.member.di.DaggerMemberComponent;
import com.sgb.member.di.MemberModule;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberCompanyHeaderBean;
import com.sgb.member.event.EventConstant;
import com.sgb.member.event.MemberEvent;
import com.sgb.member.ui.fragment.CompanyWebBiddingFragment;
import com.sgb.member.ui.fragment.CompanyWebCollectionFragment;
import com.sgb.member.ui.fragment.CompanyWebFragment;
import com.sgb.member.ui.fragment.CompanyWebProfileFragment;
import com.sgb.member.view_model.MemberCompanyWebModel;
import com.sgb.member.weight.MemberExchangePopup;
import com.sgb.member.weight.MemberTypePopup;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 会员企业网站
 */
public class MemberCompanyWebActivity extends AppActivity {

    @Inject
    MemberCompanyWebModel sModel;
    private ActivityMemberCompanyWebBinding mBinding;
    private MemberBean mMemberBean;

    private ArrayList<Fragment> mFragments;
    private MemberCompanyHeaderBean mHeaderBean;

    public static void start(Context context, MemberBean memberBean) {
        Intent intent = new Intent(context, MemberCompanyWebActivity.class);
        intent.putExtra("OBJECT", memberBean);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMemberComponent.builder()
                .appComponent(appComponent)
                .memberModule(new MemberModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mMemberBean = (MemberBean) getIntent().getSerializableExtra("OBJECT");
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_company_web);
        mBinding.setViewModel(mMemberBean);
        String[] mTabs = {"调整经营", "会员招采", "会员集采", "需求公告", "企业简介"};
        mFragments = new ArrayList<>();
        for (int i = 0; i < mTabs.length; i++) {
            switch (i) {
                case 0:
                case 3:
                    // 需求公告
                    // 调整经营
                    mFragments.add(CompanyWebFragment.newInstance(i, mMemberBean));
                    break;
                case 1:
                    // 会员招采
                    mFragments.add(CompanyWebBiddingFragment.newInstance(0, mMemberBean.getCompanyNo()));
                    break;
                case 2:
                    // 会员集采
                    mFragments.add(CompanyWebCollectionFragment.newInstance(0, mMemberBean.getCompanyNo()));
                    break;
                case 4:
                    // 企业简介
                    mFragments.add(CompanyWebProfileFragment.newInstance(0, mMemberBean));
                    break;
            }
        }
        SlidingFragmentPagerAdapter adapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTabs);
        mBinding.viewPager.setAdapter(adapter);
        mBinding.viewPager.setOffscreenPageLimit(mTabs.length);
        mBinding.tabLayout.setupWithViewPager(mBinding.viewPager);
        mBinding.tabLayout.addOnTabSelectedListener(mTabs, new XCustomTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mBinding.viewPager.setCurrentItem(tab.getPosition());
            }
        });
        mBinding.include.ivBack.setOnClickListener(v -> finish());
        mBinding.include.titleView.setText("企业网站");

        mBinding.tvCompanyName.setOnClickListener(this);
        mBinding.ivMember.setOnClickListener(this);
        mBinding.tvLetter.setOnClickListener(this);
        mBinding.tvExchange.setOnClickListener(this);
        mBinding.tvEdit.setOnClickListener(this);
        mBinding.tvTransfer.setOnClickListener(this);
        mBinding.layoutFocus.setOnClickListener(this);
        mBinding.layoutFocusAdd.setOnClickListener(this);

        // 会员类型：会员类型＝1，不显示更多标签；会员类型＞1，显示一个会员类型标签，显示更多按钮；点击更多按钮，页面弹框显示会员企业的会员类型
        List<String> allCategoryName = mMemberBean.getAllCategoryName();
        if (allCategoryName == null || allCategoryName.size() == 0) {
            mBinding.ivMember.setVisibility(View.GONE);
            mBinding.tvTopMemberType.setVisibility(View.GONE);
        } else {
            mBinding.tvTopMemberType.setVisibility(View.VISIBLE);
            mBinding.tvTopMemberType.setText(allCategoryName.get(0));
            if (allCategoryName.size() == 1) {
                mBinding.ivMember.setVisibility(View.GONE);
            } else {
                mBinding.ivMember.setVisibility(View.VISIBLE);
            }
        }
        String name = StringUtil.isEmpty(mMemberBean.getContacts()) ? "" : mMemberBean.getContacts();
        String phone = StringUtil.isEmpty(mMemberBean.getPhone()) ? "" : mMemberBean.getPhone();
        mBinding.tvTopPhone.setText(String.format("%s | %s", name, phone));

        if (StringUtil.isEmpty(mMemberBean.getLevel())) {
            mBinding.tvTopLevel.setVisibility(View.GONE);
        } else {
            mBinding.tvTopLevel.setVisibility(View.VISIBLE);
            mBinding.tvTopLevel.setText(mMemberBean.getLevel());
        }

        sModel.getCompanyWebHeadInfo(mMemberBean);
        sModel.getUserFocusCompanyStatus(mMemberBean.getCompanyId());
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onMultiClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_company_name) { // 企业名称，点击跳转到企业店铺界面
                /*Intent intent = new Intent(getActivity(), ShopInfoForCompanyTradesActivity.class);
                if (mMemberBean.getCompanyId() != null) {
                    intent.putExtra("id", mMemberBean.getCompanyId());
                    intent.putExtra("companyNo", mMemberBean.getCompanyNo());
                    intent.putExtra("position", 5);
                    startActivity(intent);
                } else {
                    MToast.showToast(getActivity(), "店铺id为空");
                }*/
            sModel.companyInfoDetail(mMemberBean);
        } else if (id == R.id.iv_member) {
            MemberTypePopup typePopup = new MemberTypePopup(this, mMemberBean.getAllCategoryName());
            new XPopup.Builder(this)
                    .asCustom(typePopup)
                    .show();
        } else if (id == R.id.tv_letter) {  // 函询
            // PickInquireByLetterActivity.start(this, "", "");
            MToast.showToast(this, "开发中");
        } else if (id == R.id.tv_exchange) { // 交流
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                // VerificationCodeLoginActivity3.start(this, EventConstant.EVENT_TENDER_DETAILS_3_JUMP);
            } else {
                // 跳转H5聊天
                if (mHeaderBean == null) {
                    sModel.getCompanyWebHeadInfo(mMemberBean);
                    return;
                }
                if (mHeaderBean.customerList != null && mHeaderBean.customerList.size() > 0) {
                    if (mHeaderBean.customerList.size() == 1) {
                        MemberCompanyHeaderBean.CustomerListBean code = mHeaderBean.customerList.get(0);
//                            NimUIKit.startP2PSession(MemberCompanyWebActivity.this, code.imAccount);
                        MemberConfig.getInstance().getInstance().startP2PSession(MemberCompanyWebActivity.this, code.imAccount);
                        return;
                    }
                    new XPopup.Builder(this)
                            .asCustom(new MemberExchangePopup(this, mHeaderBean, new MemberExchangePopup.OnConfirmListener() {
                                @Override
                                public void onConfirm(MemberCompanyHeaderBean.CustomerListBean code) {
                                    MemberConfig.getInstance().getInstance().startP2PSession(MemberCompanyWebActivity.this, code.imAccount);
                                }
                            }))
                            .show();
                } else {
                    MToast.showLongToast(getActivity(), "该企业暂未设置客服人员", Gravity.CENTER);
                }
            }
        } else if (id == R.id.tv_edit) { // 编辑
            if (mHeaderBean == null) {
                sModel.getCompanyWebHeadInfo(mMemberBean);
                return;
            }
            MemberCompanyWebEditActivity.start(this, mHeaderBean, mMemberBean, 6500);
        } else if (id == R.id.tv_transfer) { // 调级
            MemberTransferActivity.start(this, mMemberBean, -1);
        } else if (id == R.id.layout_focus) { // 已关注
            sModel.userFocus(mMemberBean.getCompanyNo(), true);
        } else if (id == R.id.layout_focus_add) { // 关注
            sModel.userFocus(mMemberBean.getCompanyNo(), false);
        }
    }

    public void updateMemberFollow(boolean isGz) {
        if (isGz) {
            mBinding.layoutFocus.setVisibility(View.VISIBLE);
            mBinding.layoutFocusAdd.setVisibility(View.GONE);
        } else {
            mBinding.layoutFocus.setVisibility(View.GONE);
            mBinding.layoutFocusAdd.setVisibility(View.VISIBLE);
        }
    }

    public MemberCompanyHeaderBean getHeaderBean() {
        return mHeaderBean;
    }

    public void setMemberProfile(MemberCompanyHeaderBean data) {
        mHeaderBean = data;
        /*// 会员类型：会员类型＝1，不显示更多标签；会员类型＞1，显示一个会员类型标签，显示更多按钮；点击更多按钮，页面弹框显示会员企业的会员类型
        List<String> allCategoryName = mHeaderBean.allCategory;
        if (allCategoryName == null || allCategoryName.size() == 0) {
            mBinding.ivMember.setVisibility(View.GONE);
            mBinding.tvTopMemberType.setVisibility(View.GONE);
        } else {
            mBinding.tvTopMemberType.setVisibility(View.VISIBLE);
            mBinding.tvTopMemberType.setText(allCategoryName.get(0));
            if (allCategoryName.size() == 1) {
                mBinding.ivMember.setVisibility(View.GONE);
            } else {
                mBinding.ivMember.setVisibility(View.VISIBLE);
            }
        }*/
        String s = mBinding.tvTopPhone.getText().toString();
        if (StringUtil.isEmpty(s)) {
            String name = StringUtil.isEmpty(mHeaderBean.mainConcat) ? "" : mHeaderBean.mainConcat;
            String phone = StringUtil.isEmpty(mHeaderBean.mainPhone) ? "" : mHeaderBean.mainPhone;
            mBinding.tvTopPhone.setText(String.format("%s | %s", name, phone));
        }
        mBinding.tvCompanyAddress.setText(mHeaderBean.businessAddress);
        /*if (StringUtil.isEmpty(data.level)) {
            mBinding.tvTopLevel.setVisibility(View.GONE);
        } else {
            mBinding.tvTopLevel.setVisibility(View.VISIBLE);
            mBinding.tvTopLevel.setText(data.level);
        }*/
    }

    public void showEmptyView() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 6500) { // 编辑企业细信息
            MemberBean bean = (MemberBean) data.getSerializableExtra("memberBean");
            mBinding.tvTopPhone.setText(String.format("%s | %s", bean.getContacts(), bean.getPhone()));
            mBinding.tvCompanyAddress.setText(mHeaderBean.businessAddress);
            mMemberBean.setContacts(bean.getContacts());
            mMemberBean.setPhone(bean.getPhone());
            int index = mFragments.size() - 1;
            Fragment fragment = mFragments.get(index);
            if (fragment instanceof CompanyWebProfileFragment) {
                ((CompanyWebProfileFragment) fragment).updateMemberInfo(bean.getCompanyName(), bean.getAddress());
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MemberEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MEMBER_UPDATE_LEVEL) {
            MemberBean bean = (MemberBean) event.getMessageData();
            mMemberBean.setLevel(bean.getLevel());
            mBinding.tvTopLevel.setText(bean.getLevel());
        }
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
